﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class PhotoCam : MonoBehaviour
{

    [Header("摄像头拍摄的照片"),]
    WebCamTexture camTexture;
    [Tooltip("显示对象")]
    public RawImage showimage;

    [Header("摄像头设备名")]
    private WebCamDevice[] devices;

     
    [Header("摄像头设备名")]
    public string deviceName; //摄像头设备名称

    [Tooltip("USB摄像头多设备时"), Space(5)]
    [Header("摄像头编号")]
    public int deviceIndex=0;

    //保存路径
    public string savePath=null;
    //名字
    public string photoname;
    public int width = 760;
    public int height = 760;

    public int fps = 30;

    
    void Start()
    {
      init();
    }

    public void init(){
        photoname = System.Guid.NewGuid().ToString("N"); 
        StartCoroutine(CallCamera());
    }   

    IEnumerator CallCamera()
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            if (camTexture != null)
                camTexture.Stop();

            devices = WebCamTexture.devices;
            if (devices.Length > 0)
            {
                deviceName = devices[deviceIndex].name;
                camTexture = new WebCamTexture(deviceName, width, height, fps);
                camTexture.Play();
                showimage.texture = camTexture;
            }

        }
    }

    public void capPoto()
    {
        Save(camTexture);
    }
    public void close()
    {
        if (camTexture != null)
            camTexture.Stop();
    }
    //对象结速
    public void OnDestroy()
    {
        close();
    }

    public Texture2D GetTexture()
    {
        Texture2D t2d = new Texture2D(camTexture.width, camTexture.height, TextureFormat.ARGB32, true);
        //将WebCamTexture 的像素保存到texture2D中
        t2d.SetPixels(camTexture.GetPixels());
        t2d.Apply();
        return t2d;
    }

    public void Save(WebCamTexture t)
    {
        if (t == null)
            return;

        Texture2D t2d = new Texture2D(t.width, t.height, TextureFormat.ARGB32, true);
        //将WebCamTexture 的像素保存到texture2D中
        t2d.SetPixels(t.GetPixels());
        //t2d.ReadPixels(new Rect(200,200,200,200),0,0,false);
        t2d.Apply();


        save(photoname, t2d,savePath);

    }

    ///图片数据
    public byte[] pngBytes()
    {
        return GetTexture().EncodeToPNG();
    }

    //转换资源
    public static Sprite toSprite(Texture2D tex)
    {
        float x = 0;
        float y = 0;
        float w = tex.width;
        float h = tex.height;

        if (tex.width > tex.height)
        {
            float th = tex.height / 2;
            w = tex.height;
            x = (tex.width - tex.height) / 2;
        }
        if (tex.width < tex.height)
        {
            float tw = tex.width / 2;
            h = tex.width;
            y = (tex.height - tex.width) / 2;
        }

        Sprite userhandSprite = Sprite.Create(tex, new Rect(x, y, w, h), Vector2.zero);
        return userhandSprite;
    }


    /// <summary>
    /// 图片转换成base64编码文本
    /// </summary>
    public static string ImgToBase64String(byte[] buffer)
    {
        return System.Convert.ToBase64String(buffer);

    }


    /// <summary>
    /// base64编码文本转换成图片
    /// </summary>
    public static Sprite Base64ToImg(string imgtring)
    {
        try
        {
            byte[] bytes = System.Convert.FromBase64String(imgtring);
            Texture2D tex2D = new Texture2D(100, 100);
            tex2D.LoadImage(bytes);
            Sprite s = Sprite.Create(tex2D, new Rect(0, 0, tex2D.width, tex2D.height), new Vector2(0.5f, 0.5f));
            return s;
        }
        catch (System.Exception )
        {
            return null;
        }

    }

     /// <summary>
    /// 保存到本地缓存的图片
    /// </summary>
    public static void save(string name, Texture2D t2d,string path)
    {
        string sp=Application.streamingAssetsPath + "/photo/" ;

        if(path.Length!=0)
           sp=path;

        //编码
        byte[] imageTytes = t2d.EncodeToPNG();
        //存储
        File.WriteAllBytes(sp + name + ".png", imageTytes);
    }

    /// <summary>
    /// 册除本地缓存的图片
    /// </summary>
    public static void delete(string name,string path)
    {
         string sp=Application.streamingAssetsPath + "/photo/" ;

        if(path.Length!=0)
           sp=path;

        string f = sp + name + ".png";
        if (File.Exists(f))
            File.Delete(f);
    }
}